/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cl.darksigns.webstat.back.ejb;

import cl.darksigns.webstat.back.exception.WebStatException;
import cl.darksigns.webstat.back.vo.WebStatSpecificVO;
import cl.darksigns.webstat.back.vo.WebStatVO;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import javax.ejb.Stateless;
import javax.jms.JMSException;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.log4j.Logger;

/**
 *
 * @author _ViKtOr
 */
@Stateless
public class GetClientMessageBean implements GetClientMessageRemote {

    Logger logger = Logger.getLogger(GetClientMessageBean.class);
    
    private String queueMessage(String webstatXML){
        Context jndiContext = null;
        Queue destino;
        QueueConnection conexion = null;
        QueueSession sesionActual;
        QueueSender enviadorMensajes;
        ObjectMessage mensaje;
        //TextMessage mensaje = null;
        logger.info("Putting Object Data Message");
        try {
            logger.info("Creating the context");
            jndiContext = new InitialContext();
        } catch (NamingException e) {
            logger.error("Error in context creation ", e);
        }

        try {
            /** Getting the QueueConnectionFactory defined in environment **/
            logger.info("Getting the QueueConnectionFactory");
            QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("jms/WebStatsQueueManager");

            /** Getting the target queue **/
            logger.info("LookUp the ReceiveQueue");
            destino = (Queue) jndiContext.lookup("jms/WebStatsReceiveQueue");

            /** Creating a queue connection **/
            logger.info("Creating a QueueConnection");
            conexion = queueConnectionFactory.createQueueConnection();

            /** Creating a queue session **/
            logger.info("Creating a QueueSession");
            sesionActual = conexion.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

            /** Creating the Sender to put the message **/
            logger.info("Creating a QueueSender");
            enviadorMensajes = sesionActual.createSender(destino);

            /** Setting properties on ObjectMessage variable **/
            mensaje = sesionActual.createObjectMessage();//createTextMessage();
            logger.info("QueueSender created");


            //mensaje.setStringProperty("TipoMensaje", "1");
            //mensaje.setObjectProperty("webstat", message);
            XStream xstream = new XStream(new DomDriver());
            Object msg = xstream.fromXML(webstatXML);
            if(msg instanceof WebStatVO){
                mensaje.setObject((WebStatVO)msg);
            }else if(msg instanceof WebStatSpecificVO){
                WebStatSpecificVO webStat;
                mensaje.setObject((WebStatSpecificVO)msg);
            }
            /** Associating the String passed as parameter to the TextMessage variable **/
            logger.info("Setting message in QueueSender");
            //mensaje.setObject(message);
            logger.info("Message set in QueueSender");
            /** Putting the message in queue **/
            long inicio = System.currentTimeMillis();
            logger.info("Putting the message in queue");

            enviadorMensajes.send(mensaje);
            enviadorMensajes.close();
            conexion.close();
            
            long fin = System.currentTimeMillis() - inicio;
            logger.info("Message sended to queue - time:" + fin + " in miliseconds");

        } catch (Exception e) {
            logger.error("Error putting the VO in queue, the data will be send directly.", e);
            logger.info("inserting data directly into DB");
        /*ProcessData process = ProcessData.getInstance();
        process.processInformation(message);
        throw new WTSException("Error living message on queue"); 	*/
        } finally {
            if (conexion != null) {
                try {
                    conexion.close();
                } catch (JMSException e) {
                    logger.error("JMSException: ", e);
                }
            }
        }
        logger.info("Program Exit");
        return "ERC_00";
    }

    public String receiveMessage(String webstatXML) {
        logger.info("XML Received ");
        queueMessage(webstatXML);
        return "ERC_00";
    }

    public String receiveSpecificMessage(String wstXML) throws WebStatException {
        logger.info("Xml received: " + wstXML);
        queueMessage(wstXML);
        return "ERC_00";
    }
    public void insertSpecificInformation(WebStatSpecificVO wst) throws WebStatException{
        
    }
    public WebStatVO[] getStandardReportFiles(String startDate, String endDate){
        return null;
    }
    public WebStatSpecificVO[] getSpecificReport(String startDate, String endDate){
        return null;
    }
    // Add business logic below. (Right-click in editor and choose
    // "EJB Methods > Add Business Method" or "Web Service > Add Operation")
}
